layui.use(['form', 'jquery', 'layer'], function() {
	let form = layui.form;
	let $ = layui.jquery;
	let layer = layui.layer;
	let quit=document.querySelector('.quit');
	let usernames=document.querySelector('.username');
	let iconImg=document.querySelector('#iconImg');
	//判断是否是登录状态
	var token=localStorage.getItem('token');
	//获取到用户名
	var username=localStorage.getItem('username');
	if(token){
		addInput();
	}else{
		//没有token重定向到登录页面
		window.location.replace("login.html");
	}
	//退出
	quit.addEventListener('click',function(e){
		layer.confirm('确定要退出吗', {icon: 3, title:'提示'}, function(index){
		localStorage.removeItem('token');
		localStorage.removeItem('username');
		//清除token并重定向到登录页面
		window.location.replace("login.html");
		  layer.close(index);
		});
		
	});
	//添加数据到页面
	function addInput(){
		var xhr = new XMLHttpRequest();
		xhr.open('get', 'http://api-breakingnews-web.itheima.net/my/userinfo');
		//客户端设置携带cookie信息
		//xhr.withCredentials=true;
		//允许客户端携带请求token信息
		xhr.setRequestHeader("Authorization",token);
		xhr.send();
		xhr.onload = function() {
			var datas=JSON.parse(xhr.responseText);
			if(datas.data.nickname!=''){
				usernames.innerHTML=datas.data.nickname;
				iconImg.src=datas.data.user_pic;
			}else{
				usernames.innerHTML='欢迎'+username;
				iconImg.src=datas.data.user_pic;
			}
		}
	}
	
});